package com.ccc3gc.servlet;

import com.ccc3gc.dao.UserDao;
import com.ccc3gc.dao.impl.UserDaoImpl;
import com.ccc3gc.entity.User;
import com.ccc3gc.util.PageUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userPage")
public class UserPageServlet extends HttpServlet {
    UserDao userDao = new UserDaoImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("UTF-8");
        String pageIndex = req.getParameter("pageIndex");
        if (pageIndex == null) {
            pageIndex = "1";
        }
        int startRow = Integer.parseInt(pageIndex);
        req.setAttribute("pageIndex", startRow);

        String keyword = req.getParameter("keyword");
        if (keyword == null) {
            keyword = "";
        }

        int totalPages = PageUtils.getTotalPages(userDao.selectUserCount(keyword));
        req.setAttribute("totalPages", totalPages);
        if (startRow < 1) {
            startRow = 1;
        }
        if (totalPages != 0 && startRow > totalPages) {
            startRow = totalPages;
        }
        req.setAttribute("keyword", keyword);
        List<User> users = userDao.selectUserByPage(startRow, PageUtils.PAGE_SIZE, keyword);
        req.setAttribute("users", users);
        req.getRequestDispatcher("/userPage.jsp").forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
